package page.actionPage;

import com.alibaba.fastjson2.JSONObject;
import javafx.fxml.FXML;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.TextField;
import utils.Constant;

public class SleepPageController extends ActionPage {
    @FXML
    private ChoiceBox<String> choiceBox;
    @FXML
    private TextField time;

    private static final String TIME_UNIT = "timeUnit";
    private static final String TIME = "time";

    public SleepPageController() {
        super("Sleep", "睡眠", Constant.TYPE.ACTION);
    }

    @Override
    public void run(JSONObject data) {
        long timeLong = Long.parseLong(data.getString(TIME));
        timeLong = switch (data.getString(TIME_UNIT)) {
            case "秒" -> timeLong * 1000;
            case "分钟" -> timeLong * 1000 * 60;
            case "小时" -> timeLong * 1000 * 60 * 60;
            default -> Long.parseLong(data.getString(TIME));
        };
        try {
            System.out.println("睡眠：" + data.getString(TIME) + data.getString(TIME_UNIT));
            Thread.sleep(timeLong);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void initAction() {
        choiceBox.getItems().addAll("秒", "毫秒", "分钟", "小时");
        choiceBox.setValue((String) db.getDataOrDefault(TIME_UNIT, "秒"));
        time.setText((String) db.getDataOrDefault(TIME, ""));
        templateController.initTemplate(submitButton -> {
            db.saveInData(TIME_UNIT, choiceBox.getValue());
            db.saveInData(TIME, time.getText());
            db.saveInData(Constant.DB.MAIN_PAGE_BUTTON_NAME, CHINESE_NAME + ":" + time.getText() + choiceBox.getValue());
            return this;
        });

    }
}
